package com.yt.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.server.PathParam;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Classname PayServiceImpl
 * @Description
 * @Date 2021/10/20 21:11
 * @Create by 杨涛
 */
@Service
@Slf4j
public class PayServiceImpl {


    public String getinfo_ok(){
        return "pay-provider Thread:"+Thread.currentThread().getName()
                +" info_ok id:"+ UUID.randomUUID();
    }

    //指定了处理问题的临时方法，和方法调用的条件，其中超时情况是3秒
    @HystrixCommand(fallbackMethod = "fallbackmd",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String getinfo_timeout(){


        //再来个出异常的
//        int i=9/0;
        try {
            TimeUnit.SECONDS.sleep(3);
//            来个超过时间的
//            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "pay-provider Thread:"+Thread.currentThread().getName()
                +" info_timeout id:"+ UUID.randomUUID();
    }



    public String fallbackmd(){
        //这个线程是hystrix独立的
        return "pay-provider Thread:"+Thread.currentThread().getName()+
                "  - hystrix - fall back method "+UUID.randomUUID();
    }
    /**
     * 熔断配置
     * 相关属性内容  HystrixCommandProperties
     */
    //circuitBreaker.enabled
    @HystrixCommand(fallbackMethod = "payCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled",value = "true"),//是否使用断路
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//访问基数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//窗口时间
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60")//错误率
    })//HystrixCommandProperties
    public String payCircuitBreaker(Integer id){
        if(id < 0){
            throw new RuntimeException("id 不能小于零。");
        }
        return Thread.currentThread().getName()+" id:" +
                id+" 调用成功："+ IdUtil.simpleUUID();
    }

    public String payCircuitBreaker_fallback(Integer id){
        return Thread.currentThread().getName()+"ID 不能小于零<br/> id:"+id+"调用失败："+ IdUtil.simpleUUID();
    }
}
